#include <glib.h>

#define TEST_ARRAY_LEN 4

static void _test_hash_str_foreach_func(gpointer key, gpointer value, gpointer user_data)
{
    g_print("%s key: %s, value: %s \n", (gchar *)user_data, (gchar *)key, (gchar *)value);
    return;
}

static void _test_hash_str_key_destroy_func(gpointer data)
{
    if(NULL != data) {
        g_free(data);
    }
}

static void _test_hash_str_value_destroy_func(gpointer data)
{
    if(NULL != data) {
        g_free(data);
    }
}

static void test_hash_iterator(void)
{
    gint i = 0;
    GHashTableIter iter;
    gpointer iter_key = NULL;
    gpointer iter_val = NULL;
    gpointer k = NULL;
    gpointer v = NULL;
    char *key[TEST_ARRAY_LEN] = {NULL};
    char *val[TEST_ARRAY_LEN] = {NULL};
    GHashTable *htable = NULL;

    g_print("\n");

    htable = g_hash_table_new_full(g_str_hash, g_str_equal, \
        _test_hash_str_key_destroy_func, _test_hash_str_value_destroy_func);

    for(i=0; i<TEST_ARRAY_LEN; i++) {
        key[i] = g_strdup_printf("key%d", i);
        val[i] = g_strdup_printf("value%d", i);
        g_hash_table_insert(htable, key[i], val[i]);
    }

    g_hash_table_foreach(htable, _test_hash_str_foreach_func, "ori");
    g_print("htable length: %d \n", g_hash_table_size(htable));

    g_hash_table_iter_init(&iter, htable);
    while(g_hash_table_iter_next(&iter, &iter_key, &iter_val)) {
        g_print("iter. key:%s value:%s \n", (char *)iter_key, (char *)iter_val);
        if(0 == g_strcmp0((char *)iter_key, "key1")) {
            g_hash_table_iter_replace(&iter, g_strdup_printf("replace-value"));
        }
        if(0 == g_strcmp0((char *)iter_key, "key2")) {
            g_hash_table_iter_remove(&iter);
        }
        if(0 == g_strcmp0((char *)iter_key, "key0")) {
            g_hash_table_iter_steal(&iter);
            g_free(iter_key);
            g_free(iter_val);
        }
    }

    g_hash_table_foreach(htable, _test_hash_str_foreach_func, "iter-replace");

    g_hash_table_destroy(htable);

    return;
}

gint main(gint argc, gchar **argv)
{
    g_test_init(&argc, &argv, NULL);

    g_test_add_func ("/hash/iterator", test_hash_iterator);

    return g_test_run();
}